/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is WOV Suite.
 *
 * The Initial Developer of the Original Code is
 * James Tuley.
 * Portions created by the Initial Developer are Copyright (C) 2008
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *           James Tuley <jay+wov@tuley.name> (WOV Suite Author)
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

#import <Cocoa/Cocoa.h>
#import <QTKit/QTKit.h>

@interface QTMovie(IdlingAdditions)
-(QTTime)maxTimeLoaded;
- (void) idle;
@end


QTMovie* movieForWOV(NSString* anOriginal,NSString* aGUID,double aPercentRange, double aPercentSoFar,NSError* tError){
	
	
	[[NSDistributedNotificationCenter defaultCenter] postNotificationName:aGUID
																   object:nil
																 userInfo:[NSDictionary dictionaryWithObjectsAndKeys:
																		   [NSNumber numberWithDouble:aPercentSoFar]
																		   ,@"Progress",[anOriginal lastPathComponent],@"File",nil] 
													   deliverImmediately:YES];
	
		
	QTDataReference* tRef= [QTDataReference dataReferenceWithReferenceToFile:anOriginal];
	QTMovie* tMovie = [[QTMovie alloc]initWithDataReference:tRef
													  error:&tError];

	
	while(NSOrderedAscending == QTTimeCompare([tMovie maxTimeLoaded],[tMovie duration])){
		
		
		NSTimeInterval tMaxLoaded;
		NSTimeInterval tDuration;
		
		QTGetTimeInterval([tMovie duration], &tDuration);
		QTGetTimeInterval([tMovie maxTimeLoaded], &tMaxLoaded);
		
		
		[[NSDistributedNotificationCenter defaultCenter] postNotificationName:aGUID
																	   object:nil
																	 userInfo:[NSDictionary dictionaryWithObjectsAndKeys:
																			   [NSNumber numberWithDouble:((tMaxLoaded/tDuration) *aPercentRange) + aPercentSoFar]
																			   ,@"Progress",nil] 
														   deliverImmediately:YES];
		
		
		[tMovie idle];
	}
	
	[[NSDistributedNotificationCenter defaultCenter] postNotificationName:aGUID
																   object:nil
																 userInfo:[NSDictionary dictionaryWithObjectsAndKeys:
																		   [NSNumber numberWithDouble:aPercentRange+aPercentSoFar]
																		   ,@"Progress",nil] 
													   deliverImmediately:YES];
	
	
	

	
	return tMovie;
}

void migrateLables(NSString* anOriginal,NSString* aWOVPath){
	
	FSRef origRef;
	FSRef wovRef;
	FSCatalogInfo origCatInfo;
	FSCatalogInfo wovCatInfo;
	NSLog(anOriginal);
	CFURLGetFSRef((CFURLRef)[NSURL fileURLWithPath:anOriginal], &origRef);
	FSGetCatalogInfo(&origRef, kFSCatInfoFinderInfo, &origCatInfo, NULL, NULL, NULL);
	
	CFURLGetFSRef((CFURLRef)[NSURL fileURLWithPath:aWOVPath], &wovRef);
	FSGetCatalogInfo(&wovRef, kFSCatInfoFinderInfo, &wovCatInfo, NULL, NULL, NULL);
	
	FileInfo* wovInfo = (FileInfo*)&wovCatInfo.finderInfo;
	FileInfo* origInfo = (FileInfo*)&origCatInfo.finderInfo;
	
	
	wovInfo->finderFlags = (wovInfo->finderFlags & ~kColor) | (origInfo->finderFlags & kColor);
	FSSetCatalogInfo(&wovRef, kFSCatInfoFinderInfo, &wovCatInfo);
	
}


int main (int argc, const char * argv[]) {
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    NSArray *args = [[NSProcessInfo processInfo] arguments];
	NSError* tError =nil;

	BOOL success = NO;
	if([args count] == 3){
		
		NSString* tWOV = [args objectAtIndex:1];
		NSString* tInfo = [tWOV stringByAppendingPathComponent:@"info.plist"];
		NSDictionary* tDict = [NSDictionary dictionaryWithContentsOfFile:tInfo];
		NSString* tMOOV = [tWOV stringByAppendingPathComponent:[tDict objectForKey:@"Moov"]];
		NSString* tOriginal = [tWOV stringByAppendingPathComponent:[tDict objectForKey:@"Standard"]];
		NSString* tLabelFrom =tOriginal;
		NSString* tGUID = [args objectAtIndex:2];
		
		[[NSDistributedNotificationCenter defaultCenter] postNotificationName:tGUID
																	   object:nil
																	 userInfo:[NSDictionary dictionaryWithObjectsAndKeys:
																			   [NSNumber numberWithInt:-1]
																			   ,@"Progress",nil] 
														   deliverImmediately:YES];
		
	
					
	
		QTMovie * tMovie =nil;
		if([[tOriginal lowercaseString] hasSuffix:@".m3u"]){
			NSString* tString =[NSString stringWithContentsOfFile:tOriginal];
			NSArray* tFiles = [tString componentsSeparatedByString:@"\r\n"];

			
			tMovie =[[[QTMovie alloc] initToWritableFile:tMOOV error:&tError] autorelease] ;
			 NSMutableArray* tChapters = [NSMutableArray array];
			int tCount=0;
			for(NSString* tPath in tFiles){
				if(![[tPath stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] isEqualToString:@""]){
					tCount++;
				}
			}
			double tPercent = 0.0;
			double tFraction =100.0/tCount;
			for(NSString* tPath in tFiles){
				
				if(![[tPath stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] isEqualToString:@""]){
				tLabelFrom =[tWOV stringByAppendingPathComponent:tPath];
				QTMovie* tAppMovie =movieForWOV([tWOV stringByAppendingPathComponent:tPath],tGUID,tFraction,tPercent,tError);
				
				[tAppMovie setSelection:QTMakeTimeRange(QTMakeTimeWithTimeInterval(0),[tAppMovie duration])];
					
					if([[tAppMovie chapters] count] <=0){
						
						[tChapters addObject:[NSDictionary dictionaryWithObjectsAndKeys:
									 tPath,QTMovieChapterName,
									 [NSValue valueWithQTTime:[tMovie duration]],QTMovieChapterStartTime,nil]];
					}
					for(NSDictionary* tChapDict in [tAppMovie chapters]){
						NSString* tName =[tChapDict objectForKey:QTMovieChapterName];
						if(tName  != nil){
						tName= [NSString stringWithFormat:@"%@: %@",tPath,tName,nil];
						
						[tChapters addObject:[NSDictionary dictionaryWithObjectsAndKeys:
											tName,QTMovieChapterName,
											  [NSValue valueWithQTTime:
											   QTTimeIncrement([[tChapDict objectForKey:QTMovieChapterStartTime] QTTimeValue]
															   ,[tMovie duration])],QTMovieChapterStartTime,nil]];
						}
					}
				[tMovie appendSelectionFromMovie:tAppMovie];
	
					tPercent+=tFraction;

				}

			}
			
			NSDictionary* tTrack =nil;
			
			for(QTTrack* tSubTrack in [tMovie tracksOfMediaType:QTMediaTypeVideo]){
				if( [[tSubTrack attributeForKey:QTTrackFormatSummaryAttribute] rangeOfString:@"subtitle" options: NSCaseInsensitiveSearch].location == NSNotFound){
				  tTrack= [NSDictionary dictionaryWithObjectsAndKeys:tSubTrack,QTMovieChapterTargetTrackAttribute,nil];
					break;
				}
			}
			
			[tMovie addChapters:tChapters 
				 withAttributes:tTrack
						  error:&tError];
	

			 
		}else{
			tMovie =movieForWOV(tOriginal,tGUID,100.0,-1.0,tError);
		}
		
		if(tError !=nil){
			goto FAILURE;
			
		}

		migrateLables(tLabelFrom,tWOV);
		
		if(![tMovie writeToFile:tMOOV withAttributes:nil])
			goto FAILURE;
		
		
		NSString* tQuickLook = [tWOV stringByAppendingPathComponent:@"QuickLook"];
		
		if(![[NSFileManager defaultManager] createDirectoryAtPath:tQuickLook attributes:nil]){
			goto FAILURE;
		}
		
		[[NSFileManager defaultManager] changeCurrentDirectoryPath:tQuickLook];
		
		
		
		NSString* tPreview = @"Preview.mov";
		
		NSString* tRelativeMoov =[@".." stringByAppendingPathComponent:[tMOOV lastPathComponent]];
		if(![[NSFileManager defaultManager] createSymbolicLinkAtPath:tPreview 
												 withDestinationPath:tRelativeMoov
															   error:&tError]){
			goto FAILURE;
		}
		
	    NSDictionary *imageAttrs = [NSDictionary dictionaryWithObjectsAndKeys:
									QTMovieFrameImageTypeNSImage, QTMovieFrameImageType,
									[NSNumber numberWithBool:YES], QTMovieFrameImageHighQuality, nil];
		
		NSImage *tImage = [tMovie frameImageAtTime:QTMakeTimeWithTimeInterval(25.0)  withAttributes:imageAttrs error:nil];

		NSData* tTiff =[tImage TIFFRepresentation];
		
		NSBitmapImageRep* tRep = [NSBitmapImageRep imageRepWithData:tTiff];
		NSData* tData = [tRep representationUsingType:NSPNGFileType 
										   properties:nil];	
		
		if(![tData writeToFile:[tQuickLook stringByAppendingPathComponent:@"Thumbnail.png"]atomically:YES])
			goto FAILURE;
		
		
		success = YES;
		
		[[NSDistributedNotificationCenter defaultCenter] postNotificationName:tGUID
																	   object:nil
																	 userInfo:[NSDictionary dictionaryWithObjectsAndKeys:
																			   [NSNumber numberWithDouble:100.0]
																			   ,@"Progress",@"",@"File",nil] 
														   deliverImmediately:YES];
		
	}
	
FAILURE:
	if(tError!=nil)
	NSLog(@"%@",tError);
	/* Do whatever cleanup is needed. */
	[pool release];
	if(success)
		exit (EXIT_SUCCESS);
	else
		exit (EXIT_FAILURE);
}
